var express = require('express');
var router = express.Router();
var async = require('async');
var moment = require('moment');
var db = require('./../../utils/db.js');
var tool = require('../../utils/tool.js');


router.get('/', function (req, res, next) {
    res.redirect('/daily/day/index')
});

router.get('/index', function (req, res, next) {
    res.render('daily/day/index')
});
//新增录入信息
router.get('/inputInfo/:id', function (req, res, next) {
    var id = req.params.id;
    res.render('daily/day/inputInfo',{
        dailyWeekPlanId:id,
    })

});
//获取录入信息
router.get('/listAll/:id', function (req, res) {
    var id = req.params.id;
    console.log(id)
    var sql = "select * from daily_day_plan where daily_week_plan_id =  '" + id + "' order by id desc";
    db.query(sql, function (err, rows) {
        if (rows && rows.length >= 0) {
            res.render('daily/day/dayListAll', {
                dailyList: rows
            });
        } else {
            res.render('error', {
                message: err.message,
                error: err

            });
        }
    });

});
router.post('/loadData', function (req, res, next) {
    var selectedTimestamp = req.body.selectedTimestamp ? req.body.selectedTimestamp : new Date().getTime();
    var isLeader = req.body.isLeader && req.body.isLeader === 'true';

    var mon = moment(parseInt(selectedTimestamp));
    var mondayStr = mon.weekday(1).format('YYYY-MM-DD');

    var sql = '';
    if (isLeader) {
        sql = "select *, (select person_name from base_user u where u.id=w.assignee_id) as assignee_name, " +
            "(select project_name from project_base p where p.id=w.project_id) as project_name, " +
            "(select (select person_name from base_user u where u.id=p.project_leader_id) from project_base p where p.id=w.project_id) as project_leader_name, " +
            "(select count(wi.id) from daily_week_plan wi where wi.project_id=w.project_id and wi.week_date='" + mondayStr + "') as project_all_num, " +
            "(select count(wi.id) from daily_week_plan wi where wi.project_id=w.project_id and wi.week_date='" + mondayStr + "' and wi.complete_time IS NOT NULL) as project_done_num " +
            "FROM daily_week_plan w where w.week_date ='" + mondayStr + "'";
    } else {
        var loginedUser = req.session.loginedUser;
        var curUserId = loginedUser.id;
        sql = "select *, (select person_name from base_user u where u.id=w.assignee_id) as assignee_name, " +
            "(select project_name from project_base p where p.id=w.project_id) as project_name, " +
            "(select (select person_name from base_user u where u.id=p.project_leader_id) from project_base p where p.id=w.project_id) as project_leader_name, " +
            "(select count(wi.id) from daily_week_plan wi where wi.project_id=w.project_id and wi.week_date='" + mondayStr + "' and w.assignee_id=" + curUserId + ") as project_all_num, " +
            "(select count(wi.id) from daily_week_plan wi where wi.project_id=w.project_id and wi.week_date='" + mondayStr + "' and w.assignee_id=" + curUserId + " and wi.complete_time IS NOT NULL) as project_done_num " +
            "FROM daily_week_plan w where w.week_date ='" + mondayStr + "' and w.assignee_id=" + curUserId;
    }

    db.query(sql, function (err, rows) {
        if (rows && rows.length >= 0) {
            var projectIdMap = {};
            var projectTaskList = [];
            for (var i = 0; i < rows.length; i++) {
                var task = rows[i];
                if (!projectIdMap[task.project_id]) {
                    projectIdMap[task.project_id] = task;
                    projectTaskList.push({
                        projectId: task.project_id,
                        projectName: task.project_name,
                        projectLeaderName: task.project_leader_name,
                        projectAllNum: task.project_all_num,
                        projectDoneNum: task.project_done_num,
                        taskList: [{
                            id:task.id,
                            taskName: task.task_name,
                            completeTime: task.complete_time ? moment(task.complete_time).format('YYYY-MM-DD HH:mm:ss') : '',
                            assigneeName: task.assignee_name,
                            remark: task.remark
                        }]
                    });
                } else {
                    for (var j = 0; j < projectTaskList.length; j++) {
                        var taskInList = projectTaskList[j];
                        if (taskInList.projectId === task.project_id) {
                            taskInList.taskList.push({
                                id:task.id,
                                taskName: task.task_name,
                                completeTime: task.complete_time ? moment(task.complete_time).format('YYYY-MM-DD HH:mm:ss') : '',
                                assigneeName: task.assignee_name,
                                remark: task.remark
                            });
                            break;
                        }
                    }

                }
            }
            res.json({
                errcode: 0,
                message: '获取日例表成功',
                data: projectTaskList
            })
        } else {
            res.json({
                errcode: 1,
                message: '获取日例表失败'
            });
        }

    });
});
//底部保存
router.post('/saveByString', function (req, res, next) {
    var contentStr = req.body.taskContent  //输入框内的内容
    if (contentStr) {
        var contentArr = contentStr.split(' ');

        var projectCode = contentArr[0];
        var taskName = contentArr[1];
        var loginName = contentArr[2];
        var remark = contentArr[3];

        var projectSql = "select id from project_base where project_code='" + projectCode + "'";
        var userSql = "select id from base_user where loginname='" + loginName + "'";

        async.series([
            function (callback) {
                db.query(projectSql, function (err, rows) {
                    callback(err, rows);
                });
            },
            function (callback) {
                db.query(userSql, function (err, rows) {
                    callback(err, rows);
                });
            }
        ], function (err, values) {
            var now = new Date();
            var nowTime = now.getTime();
            var day = now.getDay();
            var oneDayTime = 24 * 60 * 60 * 1000;
            var mondayDate = moment(nowTime - (day - 1) * oneDayTime).format('YYYY-MM-DD');
            var insertSql = "insert into daily_week_plan (task_name, remark, week_date, assignee_id, project_id) values " +
                "('" + taskName + "', '" + remark + "', '" + mondayDate + "', '" + values[0][0].id + "', '" + values[1][0].id + "')"
            db.query(insertSql, function (err, rows) {
                if (!err) {
                    console.log(rows);
                    res.json({
                        errcode: 0,
                        message: '保存成功',
                        data: rows
                    });
                } else {
                    res.json({
                        errcode: 1,
                        message: '系统内部错误'
                    })
                }
            });
        });
    } else {
        res.json({
            errcode: 2,
            message: '参数错误'
        });
    }
});
//录入信息保存
router.post('/inputInfo/save', function (req, res, next) {
    // var time = sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
    var dailyInputInfo = req.body.dailyInputInfo ? req.body.dailyInputInfo.trim() : '';
    var dailyCompleteTime = req.body.dailyCompleteTime ? req.body.dailyCompleteTime.trim() : '';
    var dailyRemarks = req.body.dailyRemarks ? req.body.dailyRemarks.trim() : '';
    // var dailyWeekPlanId = req.body.dailyWeekPlanId ? req.body.dailyWeekPlanId.trim() : '';
    var id = req.body.id ? req.body.id.trim() : '';
    var dailyWeekPlanId = req.body.dailyWeekPlanId;
    console.log(dailyWeekPlanId)
    var sql = '';
    if (id) {
        sql = "update daily_day_plan set daily_input_info = '" + dailyInputInfo + "',daily_complete_time = '" + dailyCompleteTime + "',daily_remarks = '" + dailyRemarks + "',daily_week_plan_id = '" + dailyWeekPlanId + "' where id = " + id + "";
    } else {
        sql = "insert into daily_day_plan(daily_input_info,daily_complete_time,daily_remarks,daily_week_plan_id) " +
            "values('" + dailyInputInfo + "','" + dailyCompleteTime + "','" + dailyRemarks + "','" + dailyWeekPlanId + "')";

    }
    db.query(sql, function (err, rows) {
        if (rows) {
            res.redirect("/daily/day/index");
        } else {
            res.json({
                errcode: 1,
                massage: "保存失败"
            });
        }
    });
});
module.exports = router;